using System;
using System.Data;
using System.IO;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace Framework.Repository.Testing
{
    public sealed class SqlitePersistence : IPersistence
    {
        private IDbConnection keepAliveConnectionToAvoirRandomErrorDueToGcAndSqlite;

        public IPersistenceConfigurer CreateConfigurer()
        {
            var connectionString = string.Format("FullUri=file:{0}.db?mode=memory&cache=shared;Pooling=True;Max Pool Size=100;", Path.GetRandomFileName());

            Console.WriteLine("    using connection string : {0}", connectionString);

            return SQLiteConfiguration.Standard
                .ShowSql()
                .ConnectionString(connectionString);
        }

        public void BuildSchema(ISessionFactory sessionFactory, Configuration configuration)
        {
            keepAliveConnectionToAvoirRandomErrorDueToGcAndSqlite = sessionFactory.OpenSession().Connection;
            new SchemaExport(configuration).Execute(true, true, false, keepAliveConnectionToAvoirRandomErrorDueToGcAndSqlite, null);
        }

        public void Dispose()
        {
            keepAliveConnectionToAvoirRandomErrorDueToGcAndSqlite.Close();
        }
    }
}